package com.cloudcc.mobile.db;

import java.util.List;

import android.content.Context;

import com.cloudcc.mobile.entity.Message;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

/**
 * 消息管理 每个用户id一个db数据库文件
 * 
 * @author wangzhiqiang
 * @date 2015-6-8 下午2:32:27
 * 
 */
public class MessageDB {
	private Context context;
	private DbUtils db;

	public MessageDB(Context context, String dbName) {
		db = DbUtils.create(context, dbName);
		this.context = context;
	}

	/**
	 * 保存数据库
	 * 
	 * @param cls
	 * @throws DbException
	 */
	public void saveMessage(Message entity) throws DbException {
		db.save(entity);
	}

	public void saveListMessage(List<Message> list) throws DbException {
		db.saveAll(list);
	}

	/**
	 * 查询所有消息
	 * 
	 * @param <T>
	 */
	public <T> List<Message> findAllMessage(Class<T> cls) throws DbException {
		@SuppressWarnings("unchecked")
		List<Message> list = (List<Message>) db.findAll(cls);
		return list;
	}

	/**
	 * 删除某个id的消息
	 * 
	 * @param <T>
	 * @throws DbException
	 */
	public <T> void deleteById(Class<T> cls, int id) throws DbException {
		db.deleteById(cls, id);
	}

	/**
	 * 删除所有消息
	 * 
	 * @param <T>
	 * @throws DbException
	 */
	public <T> void deleteAll(Class<T> cls) throws DbException {
		db.deleteAll(cls);
	}

	/**
	 * 获取系统新消息数量
	 * 
	 * @param <T>
	 * @throws DbException
	 */

	public long getNewMessageNum() throws DbException {
		if (isExit()) {
			long num = db.count(Selector.from(Message.class).where("isNew",
					"=", "1"));
			return num;
		} else {
			return 0;
		}
	}

	/**
	 * 清空消息数量
	 * 
	 * @throws DbException
	 */

	public void clearMessageNum() throws DbException {
		List<Message> list = db.findAll(Selector.from(Message.class));
		for (int i = 0; i < list.size(); i++) {
			list.get(i).setIsNew("0");
		}
		db.saveOrUpdateAll(list);
	}

	/**
	 * 判别是否存在
	 * 
	 * @return
	 * @throws DbException
	 */
	public boolean isExit() throws DbException {
		boolean istable = db.tableIsExist(Message.class);
		if (istable) {
			long a = db.count(Message.class);
			if (a > 0) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	public Message getLastMessage() throws DbException {
		if (isExit()) {
			List<Message> list = db.findAll(Message.class);
			return list.get(list.size() - 1);
		} else {
			return null;
		}

	}
}
